from bot.enterprise_wechat_gpt.util.tair_util import *


def set_transfer(user_id, transfer):
    # if transfer == 'false':
    #     return
    tair_util.set_expire("QW:Transfer:" + user_id, transfer, 30 * 24 * 3600)


def get_transfer(user_id):
    transfer = tair_util.get("QW:Transfer:" + user_id)
    if transfer is None:
        return False
    return transfer == 'true'


def mark_from_agent_to_ai(user_id):
    tair_util.set_expire("QW:TransferToAI:" + user_id, 'true', 60)


def is_mark_from_agent_to_ai(user_id):
    return tair_util.get("QW:TransferToAI:" + user_id) == 'true'


def compute_transfer_rate(output):
    try:
        if output.get('transfer', False):
            date = datetime.datetime.now().strftime("%m:%d")
            count_key = "QW:TS:Count:" + date
            rate_key = "QW:TS:Rate:" + date
            tair_util.hincr(count_key, "Total")
            transfer_reason = output['text']['content']
            reason_list = ["信用卡", "白条", "分分卡", "黑卡", "小金库", "优惠", "情绪", "新用户", "消息类型不是文本", "平台",
                           "发截图", "AI言辞不当", "群发激活", "人工", "怀疑", "大额客户", "以贷还贷", "逾期"]
            for r in reason_list:
                if r in transfer_reason:
                    tair_util.hincr(count_key, r)
                    break
            else:
                tair_util.hincr(count_key, "其他")
            reason_list.append("其他")
            for r in reason_list:
                m = tair_util.hget(count_key, r)
                if m is None:
                    continue
                n = tair_util.hget(count_key, "Total")
                tair_util.hset(rate_key, r, str(int(m) / int(n)))
    except Exception as e:
        logging.error(f"统计转接率异常:{e}{traceback.format_exc()}")


if __name__ == '__main__':
    set_transfer('123', 'false')
    print(get_transfer('123'))
    # mark_from_agent_to_ai('123')
    # print(is_mark_from_agent_to_ai('123'))

    output = {
        'msgtype': 'text',
        'text': {'content': '信用卡'},
        'transfer': True
    }
    compute_transfer_rate(output)


